from django.db import models
import os
import uuid
from datetime import datetime


def upload_to(instance, filename):
    ext = os.path.splitext(filename)[1]  # 获取文件扩展名（如 .txt）
    return os.path.join(
        datetime.now().strftime("%Y%m%d"),  # 按年月日分目录
        f"{uuid.uuid4().hex}{ext}"  # 仅使用 UUID + 扩展名
    )


class Upload(models.Model):
    file = models.FileField(verbose_name='上传文件', help_text='上传文件', upload_to=upload_to)
    file_name = models.CharField(verbose_name='文件名', help_text='文件名', null=True, default=None, max_length=100)
    file_size = models.CharField(verbose_name='文件大小', help_text='文件大小', null=True, default=None, max_length=20)
    file_type = models.CharField(verbose_name='文件类型', help_text='文件类型', null=True, default=None, max_length=20)
    create_time = models.DateTimeField(verbose_name='创建时间', help_text='创建时间', auto_now_add=True)
    create_user = models.ForeignKey(verbose_name='创建人', help_text='创建人', to='users.User',
                                    on_delete=models.CASCADE, related_name='uploads')

    class Meta:
        db_table = 'tb_upload'
        verbose_name = 'tb_upload'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.file.name
